/**
 * 维护内部联系人
 */
import type { BaseContact } from '@/services/contacts'
import { ContactType } from '@/services/contacts'
import { ContactTypeService, type LoadInfoConditions } from '../common/ContactTypeService'
import { getPeopleContactInfo } from '../common/api'
import { getInternals } from './api'
import { Search } from './search'

export * from './api'

export interface InternalContact extends BaseContact {
  type: ContactType.internal
  sex: 1 | 2 // 性别，1 男  2 女
}

export class Internals extends ContactTypeService<InternalContact> {
  constructor() {
    super('internals')
  }

  search = new Search()

  get pageSize() {
    return 300
  }

  async request({ wxids, page, pageSize }: { wxids: string[]; page: number; pageSize: number }) {
    return getInternals({ wxids, page, pageSize })
  }

  async tryLoadInfo({ id, ownerWxid, byChatRecord }: LoadInfoConditions) {
    const qywxCorpId = this.qywxs.alives.value.get(ownerWxid)?.corpid
    if (qywxCorpId === undefined) {
      this.logger.warn('找不到对应企业微信，无法加载员工资料', id)
      return false
    }

    const res = await getPeopleContactInfo(id, qywxCorpId)
    if (res.success && res.data?.type === ContactType.internal) {
      const contact = res.data
      // 后端返回的联系人资料的“最近联系时间”和“最新聊天内容”可能不是最新的，此时用 byChatRecord 代替
      if (byChatRecord && contact.contacted < byChatRecord.timestamp) {
        contact.contacted = byChatRecord.timestamp
        contact.latestChat = byChatRecord
      }
      this.listAddOrUpdate(contact)
      return true
    }
    return false
  }
}
